package cn.edu.tjufe.llp.tin.model.sys;

import java.util.HashSet;
import java.util.Set;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.FetchType;
import javax.persistence.Index;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.PrePersist;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;
import javax.persistence.JoinColumn;
import javax.persistence.ForeignKey;

import cn.edu.tjufe.llp.tin.enums.user.AccountEnabled;
import cn.edu.tjufe.llp.tin.enums.user.AccountExpired;
import cn.edu.tjufe.llp.tin.enums.user.AccountLocked;
import cn.edu.tjufe.llp.tin.enums.user.CredentialsExpired;
import cn.edu.tjufe.llp.tin.model.BaseEntity;
import lombok.Getter;
import lombok.Setter;

@Getter
@Setter
@Entity
@Table(name = "sys_user", indexes = {
		@Index(columnList = "username, deleted", name = "ux_sys_user_username", unique = true) }, uniqueConstraints = {
				@UniqueConstraint(columnNames = { "username", "deleted" }, name = "uc_sys_user_username") })
public class SysUser extends BaseEntity {

	
	/**
	 * 
	 */
	private static final long serialVersionUID = -7835274504789057180L;

	@Column(nullable = false, length = 32)
	private String username;

	@Column(nullable = false, length = 80)
	private String password;

	@Column(nullable = false, length = 32)
	private String nickname;

	@Column(nullable = false, length = 32)
	private String realname;

	@Column(length = 32)
	private String phone;

	@Column(length = 32)
	private String email;

	@Column(length = 80)
	private String photo;

	@Column(nullable = false, length = 1)
	@Enumerated(EnumType.STRING)
	private AccountEnabled enabled;

	@Column(nullable = false, length = 1)
	@Enumerated(EnumType.STRING)
	private AccountExpired expired;

	@Column(nullable = false, length = 1)
	@Enumerated(EnumType.STRING)
	private AccountLocked locked;

	@Column(name = "creds_expired", nullable = false, length = 1)
	@Enumerated(EnumType.STRING)
	private CredentialsExpired credentialsExpired;

	@ManyToMany(fetch = FetchType.LAZY, cascade = CascadeType.MERGE)
	@JoinTable(name = "sys_user_role", 
			joinColumns = { @JoinColumn(name = "user_id", foreignKey = @ForeignKey(name = "FK_sys_user_role_user"), nullable = false, updatable = false) }, 
			inverseJoinColumns = { @JoinColumn(name = "role_id", foreignKey = @ForeignKey(name = "FK_sys_user_role_role"), nullable = false, updatable = false) })
	private Set<SysRole> roles = new HashSet<>(0);
	
	@PrePersist
	protected void prePersist(){
		super.prePersist();
		
		enabled = AccountEnabled.T;
		expired = AccountExpired.F;
		locked = AccountLocked.F;
		credentialsExpired = CredentialsExpired.F;
	}

}
